package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author itheima
 * @since 2022-07-17
 */
@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient articleClient;

    @Override
    @Async
    public void autoScanWmNews(Long newsId) throws Exception {

        // 0. 入参判空
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }

        // 1. 查询新闻信息
        // 1.1 新闻为空 -> 响应失败
        WmNews wmNews = wmNewsService.getById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }

        // 2. 提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);

        // 3. 提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imageList = getImages(images, content);

        // 4. 调用文字审核接口
        // 4.1 审核失败 -> wmNews修改方法
        // 4.2 审核不确定 -> wmNews修改方法
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(textScan, null, newsId.intValue());
        if (!textScanResult) {
            log.warn("文字审核失败");
            return;
        }

        // 5. 调用图片审核接口
        // 5.1 审核失败 -> wmNews修改方法
        // 5.2 审核不确定 -> wmNews修改方法
        Map imageScan = greenImageScan.imageScan(imageList);
        Boolean imageScanResult = checkResult(imageScan, null, newsId.intValue());
        if (!imageScanResult) {
            log.warn("图片审核失败");
            return;
        }

        // 6. 远程调用ArticleClient保存文章
        // 6.1 判断响应结果是不是200
        ArticleDto dto = wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("文章保存失败");
            return;
        }

        Long articleId = (Long) responseResult.getData();

        // 7. 将articleid回写到wmNews表中
        updateWmNews(9, "审核通过", articleId, newsId.intValue());
    }

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmUserService wmUserService;

    private ArticleDto wmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        dto.setLayout(wmNews.getType());

        // 查询渠道的名称
        Integer channelId = wmNews.getChannelId();
        if (channelId != null) {
            WmChannel channel = wmChannelService.getById(channelId);
            if (channel != null) {
                dto.setChannelName(channel.getName());
            }
        }

        // 获取作者名
        Integer userId = wmNews.getUserId();
        if (userId != null) {
            dto.setAuthorId(userId.longValue());
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser != null) {
                dto.setAuthorName(wmUser.getName());
            }
        }

        return dto;
    }

    private Boolean updateWmNews(Integer status, String reason, Long articleId, Integer newsId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }

        return wmNewsService.updateById(wmNews);
    }

    private Boolean checkResult(Map result, Long articleId, Integer newsId) {
        if (CollectionUtils.isEmpty(result)) {
            log.warn("审核结果为空");
            return true;
        }

        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)) {
            return true;
        } else if ("block".equals(suggestion)) {
            // 更新wmNews状态
            updateWmNews(2, "未通过", articleId, newsId);
            return false;
        } else if ("review".equals(suggestion)) {
            updateWmNews(3, "转人工审核", articleId, newsId);
            return false;
        }

        return true;
    }

    private List<byte[]> getImages(String images, String content) {
        // 0. 声明总的图片集合
        List<String> finalList = new ArrayList<>();

        // 1. 提取封面图 -> List<String>
        if (StringUtils.isNotBlank(images)) {
            String[] split = images.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                List<String> list = Arrays.asList(split);

                // 加入到大的集合中
                finalList.addAll(list);
            }
        }

        // 2. 提取内容图 -> List<String>
        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map item : maps) {
                    if (CollectionUtils.isEmpty(item)) {
                        continue;
                    }

                    Object type = item.get("type");
                    if ("image".equals(type)) {
                        String value = (String) item.get("value");
                        finalList.add(value);
                    }
                }
            }
        }

        // 组装最后要输出的结果
        List<byte[]> result = new ArrayList<>();
        // 3. 遍历List<String>，使用MinioTemplate.download，转成List<byte[]>
        if (!CollectionUtils.isEmpty(finalList)) {
            for (String url : finalList) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }

                byte[] bytes = minIoTemplate.downLoadFile(url);
                result.add(bytes);
            }
        }

        // 4. 返回集合
        return result;
    }


    private String getText(String title, String content) {
        if (StringUtils.isBlank(content)) {
            return title;
        }

        // 1. 提取content里面的文字内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return title;
        }

        StringBuilder builder = new StringBuilder();
        for (Map item : maps) {
            if (CollectionUtils.isEmpty(item)) {
                continue;
            }

            Object type = item.get("type");
            if ("text".equals(type)) {
                String value = (String) item.get("value");
                builder.append(value);
            }
        }

        // 2. 将content文字内容和title进行组合
        builder.append("_").append(title);

        // 3. 返回组合后的结果
        return builder.toString();
    }

}
